package com.yssoft.utils;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 陈翼东
 * @说明 实体转换
 * @time 2018/4/28 下午 04:59
 */
public class ObjectConversion {
    
    /**
     * 实体转换成json
     * @param t
     * @return
     * @throws IllegalAccessException
     */
    public static JSONObject getObjectToJSON(Object t) throws IllegalAccessException {
            Class className = t.getClass();
            JSONObject jsonObject=new JSONObject();
            for(; className != Object.class ; className = className.getSuperclass()) {
                Field[] fields = className.getDeclaredFields();//获取所有私有字段
                for (Field field : fields) {
                    field.setAccessible(true);
                    jsonObject.put(field.getName(), field.get(t)==null?"":field.get(t));
                }
            }
        return jsonObject;
    }
    
    /**
     * 实体转换成map
     * @param t
     * @return
     * @throws IllegalAccessException
     */
    public static  Map<String,Object> getObjectToMap(Object t) throws IllegalAccessException {
            Class className = t.getClass();
            Map<String,Object> param=new HashMap<>();
            for(; className != Object.class ; className = className.getSuperclass()) {
                Field[] fields = className.getDeclaredFields();//获取所有私有字段
                for (Field field : fields) {
                    field.setAccessible(true);
                    param.put(field.getName(), field.get(t)==null?"":field.get(t));
                }
            }
        return param;
    }
    /**
     * list<object>实体转换成List<Map<String,Object>>
     * @param tList
     * @return
     * @throws IllegalAccessException
     */
    public static List<Map<String,Object>>getListObjectToListMap(List<?> tList) throws IllegalAccessException {
        List<Map<String,Object>> result=new ArrayList<>();
        for (Object o : tList) {
            Class className = o.getClass();
            Map<String,Object> param=new HashMap<>();
            for(; className != Object.class ; className = className.getSuperclass()) {
                Field[] fields = className.getDeclaredFields();//获取所有私有字段
                for (Field field : fields) {
                    field.setAccessible(true);
                    param.put(field.getName(), field.get(o)==null?"":field.get(o));
                }
            }
            result.add(param);
        }
        return result;
    }
    
}
